#!/bin/bash
# OY 项目服务器初始化脚本
# 在 CentOS 服务器上执行此脚本来安装和配置 Nginx

set -e  # 遇到错误立即退出

echo "=================================="
echo "🚀 OY 项目服务器环境初始化"
echo "=================================="

# 检查是否为 root 用户
if [ "$EUID" -ne 0 ]; then 
    echo "❌ 请使用 root 用户或 sudo 执行此脚本"
    exit 1
fi

# 1. 修复 CentOS 镜像源（使用阿里云镜像）
echo ""
echo "🔧 修复 CentOS 镜像源..."

# 备份原有源
mkdir -p /etc/yum.repos.d/backup
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/ 2>/dev/null || true

# 检测 CentOS 版本
if grep -q "CentOS Linux 8\|CentOS Stream 8" /etc/centos-release 2>/dev/null; then
    echo "检测到 CentOS 8，使用阿里云镜像源..."
    
    # 直接创建 CentOS 8 配置文件
    cat > /etc/yum.repos.d/CentOS-Base.repo << 'EOF'
[base]
name=CentOS-8.5.2111 - Base - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos-vault/8.5.2111/BaseOS/$basearch/os/
gpgcheck=0

[appstream]
name=CentOS-8.5.2111 - AppStream - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos-vault/8.5.2111/AppStream/$basearch/os/
gpgcheck=0

[extras]
name=CentOS-8.5.2111 - Extras - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos-vault/8.5.2111/extras/$basearch/os/
gpgcheck=0
EOF
    
    echo "✅ CentOS 8 已切换到阿里云镜像"

elif grep -q "CentOS Linux 7" /etc/centos-release 2>/dev/null; then
    echo "检测到 CentOS 7，使用阿里云镜像源..."
    
    # 直接创建 CentOS 7 配置文件
    cat > /etc/yum.repos.d/CentOS-Base.repo << 'EOF'
[base]
name=CentOS-7 - Base - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos/7/os/$basearch/
gpgcheck=0

[updates]
name=CentOS-7 - Updates - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos/7/updates/$basearch/
gpgcheck=0

[extras]
name=CentOS-7 - Extras - mirrors.aliyun.com
baseurl=https://mirrors.aliyun.com/centos/7/extras/$basearch/
gpgcheck=0
EOF
    
    echo "✅ CentOS 7 已切换到阿里云镜像"
fi

# 清理缓存并重建
echo "清理缓存..."
yum clean all 2>/dev/null || true
rm -rf /var/cache/yum/* /var/cache/dnf/* 2>/dev/null || true

echo "重建缓存..."
yum makecache 2>/dev/null || yum makecache timer 2>/dev/null || true

# 2. 更新系统（可选，失败不影响后续安装）
echo ""
echo "📦 正在更新系统..."
yum update -y || echo "⚠️  系统更新失败，继续安装..."

# 3. 安装 Nginx
echo ""
echo "📦 正在安装 Nginx..."
yum install -y nginx

# 4. 安装 unzip（用于解压部署文件）
echo ""
echo "📦 正在安装 unzip..."
yum install -y unzip

# 5. 创建项目目录
echo ""
echo "📁 创建项目目录..."
mkdir -p /var/www/oy-promotion
chown -R nginx:nginx /var/www/oy-promotion
chmod -R 755 /var/www/oy-promotion

# 6. 配置防火墙
echo ""
echo "🔥 配置防火墙..."
if systemctl is-active --quiet firewalld; then
    echo "防火墙已启用，正在开放 HTTP/HTTPS 端口..."
    firewall-cmd --permanent --add-service=http
    firewall-cmd --permanent --add-service=https
    firewall-cmd --reload
    echo "✅ 防火墙配置完成"
else
    echo "⚠️  防火墙未启用，跳过配置"
fi

# 7. 配置 SELinux（CentOS 特有）
echo ""
echo "🔒 配置 SELinux..."
if [ -f /etc/selinux/config ]; then
    setenforce 0
    sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
    echo "✅ SELinux 已禁用（需要重启生效）"
fi

# 8. 创建 Nginx 站点配置
echo ""
echo "⚙️  创建 Nginx 站点配置..."
cat > /etc/nginx/conf.d/oy-promotion.conf << 'EOF'
server {
    listen 80;
    server_name _;
    
    root /var/www/oy-promotion;
    index index.html;
    
    # 支持 SPA 路由
    location / {
        try_files $uri $uri/ /index.html;
    }
    
    # API 代理（如果需要）
    location /api/ {
        proxy_pass http://localhost:8000/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
    # 静态资源缓存
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    
    # Gzip 压缩
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_min_length 1000;
    
    # 日志
    access_log /var/log/nginx/oy-promotion.access.log;
    error_log /var/log/nginx/oy-promotion.error.log;
}
EOF

echo "✅ Nginx 配置文件已创建: /etc/nginx/conf.d/oy-promotion.conf"

# 9. 测试 Nginx 配置
echo ""
echo "🔍 测试 Nginx 配置..."
nginx -t

# 10. 启动 Nginx
echo ""
echo "🚀 启动 Nginx..."
systemctl start nginx
systemctl enable nginx

# 11. 检查 Nginx 状态
echo ""
echo "🔍 检查 Nginx 状态..."
if systemctl is-active --quiet nginx; then
    echo "✅ Nginx 运行正常"
else
    echo "❌ Nginx 启动失败"
    systemctl status nginx
    exit 1
fi

# 12. 显示服务器信息
echo ""
echo "=================================="
echo "✅ 服务器环境初始化完成！"
echo "=================================="
echo ""
echo "📊 系统信息："
echo "  - Nginx 版本: $(nginx -v 2>&1 | cut -d'/' -f2)"
echo "  - 项目目录: /var/www/oy-promotion"
echo "  - 配置文件: /etc/nginx/conf.d/oy-promotion.conf"
echo ""
echo "🌐 服务器 IP 地址："
ip addr show | grep "inet " | grep -v 127.0.0.1 | awk '{print "  - " $2}' | cut -d'/' -f1
echo ""
echo "📝 下一步操作："
echo "  1. 在本地运行: .\deploy-simple.ps1 部署项目"
echo "  2. 访问: http://$(ip addr show | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' | cut -d'/' -f1 | head -n1)"
echo ""
echo "🔧 常用命令："
echo "  - 查看日志: tail -f /var/log/nginx/oy-promotion.error.log"
echo "  - 重启 Nginx: systemctl restart nginx"
echo "  - 测试配置: nginx -t"
echo ""
echo "=================================="
